import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Spin, Row, Col, message } from 'antd';
import {
  WeaTools,
  WeaOrgTree,
  WeaInputSearch,
  WeaAvatar,
  WeaNewScrollPagination,
  WeaLocaleProvider,
  WeaAlertPage,
  WeaErrorPage,
} from 'ecCom';
import { noRepeat } from '../../util/index';

const { tryCatch, callApi } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
const MAILPAGENAME = 'INTERNALCONTACTSTREE';

/* type类型匹配
  1 subcom 分部
  2 dept 部门
  3 resource 人员
  特殊类型
  0 根节点
  all 所有人 */
const getType = {
  2: 'dept',
  1: 'subcom',
  3: 'resource',
};
const getIdFocus = {
  sendTo_internal: 'internaltonewIds',
  sendCc_internal: 'internalccnewIds',
  sendBcc_internal: 'internalbccnewIds',
};
@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@eshmdo`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject('emailNewStore')
@observer
class InternalContactsTree extends React.PureComponent {
  constructor(props) {
    super(props);
    this.prefixCls = 'wea-email-new-contacts-internalTree';
    this.state = {
      loading: false,
      dataList: [],
      isSearch: false,
      listloading: false,
      searchValue: '',
    };
    this.getTreeParams = {};
  }

  componentDidMount() {
    const {
      emailNewStore: { setState },
    } = this.props;
    setState({ refreshTree: this.refreshTree });
  }

  getDatas = (Methods) => {
    let res = callApi(
      '/api/public/browser/data/17',
      Methods,
      this.getTreeParams,
    );
    return res;
  };

  refreshTree = () => {
    this.setState(
      {
        loading: true,
        dataList: [],
        isSearch: false,
        listloading: false,
        searchValue: '',
      },
      () => {
        this.setState({ loading: false });
      },
    );
    this.getTreeParams = {};
  };

  getEmailIds = () => {
    const {
      emailNewStore,
      emailNewStore: { focusTagGroup: f },
    } = this.props;
    const focusTagGroup = f || 'sendTo_internal';
    return toJS(emailNewStore[getIdFocus[focusTagGroup]]);
  };

  setEmailData = (arr, ids = []) => {
    const {
      emailNewStore,
      emailNewStore: { setState, focusTagGroup: f },
    } = this.props;
    const focusTagGroup = f || 'sendTo_internal';
    const newArr = noRepeat([...toJS(emailNewStore[focusTagGroup]), ...arr]);
    const _ids = [
      ...new Set([toJS(emailNewStore[getIdFocus[focusTagGroup]]), ...ids]),
    ];
    setState({ [focusTagGroup]: newArr, [getIdFocus[focusTagGroup]]: _ids });
  };

  treeNodeClick = (event, ids, nodeids, nodes) => {
    const { type, id } = event.node.props;
    // // 判断是否是父节点
    let resourceNodes = nodes.map((v) => {
      if (v.type === '3') {
        return { ...v, type: 'resource' };
      }
      return v;
    });
    if (type === '3') {
      if (this.getEmailIds().indexOf(id) > -1) {
        message.error(getLabel('517402', '人员已被选'));
      } else {
        this.setEmailData(resourceNodes, ids);
      }
    }
  };

  onDoubleClick = (node) => {
    this.getTreeParams = {
      virtualtype: 1,
      status: 8,
      cmd: 'resource',
      types: (getType[node.type] && `${getType[node.type]}|${node.id}`) || '',
    };
    let ids = [];
    if (node.type !== '3' && node.type !== '0') {
      this.getDatas('POST').then((res) => {
        let newArr = res.datas.map((v) => {
          if (!v.users.length) {
            message.error(
              getLabel('517424', '您所选择的 分部|部门 没有人员可添加！'),
            );
            return null;
          }
          ids = v.users.map(item => item.id);
          const userids = ids.join(',');
          return { ...v, lastname: node.name, userids };
        });
        if (newArr[0]) {
          this.setEmailData(newArr, ids);
        }
        this.getTreeParams = {};
      });
    }
  };

  onlistDoubleClick = (item) => {
    const resourceNodes = [{ ...item, type: 'resource' }];
    if (this.getEmailIds().indexOf(item.id) > -1) {
      message.error(getLabel('517402', '人员已被选'));
    } else {
      this.setEmailData(resourceNodes, [item.id]);
    }
  };

  onSearch = (v) => {
    this.setState({ isSearch: v });
    if (v) {
      this.setState({ dataList: [], loading: true });
      this.getTreeParams = {
        pageSize: 20,
        current: 1,
        min: 1,
        max: 20,
        lastname: v,
        virtualtype: 1,
        cmd: 'search',
        isNoAccount: 1,
      };
      this.getDatas('GET').then((res) => {
        if (res.status) {
          const dataList = res.datas || [];
          this.setState({ dataList, loading: false });
        }
      });
    }
  };

  onScrollEnd = () => {
    this.getTreeParams = {
      ...this.getTreeParams,
      current: this.getTreeParams.current + 1,
      min: this.getTreeParams.max + 1,
      max: this.getTreeParams.max + this.getTreeParams.pageSize,
    };
    this.setState({ listloading: true });
    this.getDatas('GET').then((res) => {
      if (res.status) {
        const dataList = res.datas || [];
        this.setState({
          dataList: [...this.state.dataList, ...dataList],
          listloading: false,
        });
      }
    });
  };
  render() {
    const {
      dataList,
      loading,
      isSearch,
      listloading,
      searchValue,
    } = this.state;
    return (
      <div className={this.prefixCls}>
        <div className={`${this.prefixCls}-search`}>
          <WeaInputSearch
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaInputSearch@hc84bz`}
            value={searchValue}
            placeholder={getLabel('507615', '请输入人员姓名/首字母')}
            onSearchChange={(v) => {
              this.setState({ searchValue: v });
              this.onSearch(v);
            }}
            onSearch={this.onSearch}
          />
        </div>
        {loading && (
          <Spin
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Spin@5hem7z`}
          />
        )}
        {!loading && !isSearch && (
          <div className={`${this.prefixCls}-tree`}>
            <WeaOrgTree
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaOrgTree@c38bpu`}
              dataUrl="/api/hrm/base/getHrmSearchTree"
              isLoadSubDepartment
              isLoadUser
              treeNodeClick={this.treeNodeClick}
              onDoubleClick={this.onDoubleClick}
              vtreeMode
            />
          </div>
        )}
        {!loading && isSearch && (
          <div className={`${this.prefixCls}-list`}>
            {dataList && dataList.length === 0 ? (
              <WeaAlertPage
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaAlertPage@nzqx9b`}
                icon="icon-coms-blank"
              >
                <div style={{ color: '#000' }}>
                  {getLabel(83320, '没有可显示的数据')}
                </div>
              </WeaAlertPage>
            ) : (
              <WeaNewScrollPagination
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaNewScrollPagination@zqlz05`}
                height={'100%'}
                loading={listloading}
                offset={100}
                onScrollEnd={this.onScrollEnd}
              >
                <ul>
                  {dataList &&
                    dataList.map(item => (
                      <li
                        className={`${this.prefixCls}-list-line`}
                        key={item.id}
                        onDoubleClick={() => this.onlistDoubleClick(item)}
                      >
                        <Row
                          ecId={`${
                            (this && this.props && this.props.ecId) || ''
                          }_Row@5a61ft@${MAILPAGENAME}${item.id}`}
                        >
                          <Col
                            ecId={`${
                              (this && this.props && this.props.ecId) || ''
                            }_Col@to5k33@${MAILPAGENAME}${item.id}avatar`}
                            className={`${this.prefixCls}-list-avatar`}
                            span={4}
                          >
                            <WeaAvatar
                              ecId={`${
                                (this && this.props && this.props.ecId) || ''
                              }_WeaAvatar@kuq4b9@${MAILPAGENAME}avatar`}
                              url={item.img}
                              userId={item.id}
                              name={item.lastname}
                              type="1"
                              style={{ width: 40, height: 40 }}
                            />
                          </Col>
                          <Col
                            ecId={`${
                              (this && this.props && this.props.ecId) || ''
                            }_Col@dwzqn5@${MAILPAGENAME}${item.id}userinfo`}
                            span={20}
                            className={`${this.prefixCls}-list-userinfo`}
                          >
                            <div>
                              <span title={item.lastname}>{item.lastname}</span>
                              <span title={item.jobtitlename}>
                                {item.jobtitlename}
                              </span>
                            </div>
                            <div className="dept">
                              <span title={item.departmentname}>
                                {item.departmentname}
                              </span>
                              <span title={item.subcompanyname}>
                                {item.subcompanyname}
                              </span>
                            </div>
                          </Col>
                        </Row>
                      </li>
                    ))}
                </ul>
              </WeaNewScrollPagination>
            )}
          </div>
        )}
      </div>
    );
  }
}

export default InternalContactsTree;
